All files / src/app/api/collections/[id]/dispositions route.ts

96.66% Statements 29/30
100% Branches 18/18
100% Functions 2/2
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                16x 16x 16x   15x 15x   14x   14x 14x 12x   11x 11x 8x   3x         6x 6x 6x 5x 5x 5x 4x 6x     4x    
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { requireApiItemCapability, requireApiCollectionAccess } from "@/server/dal/collection-access";
import { DispositionController } from "@/server/api/dispositions";
import { errorResponse } from "@/server/api/http-errors";
 
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getSession();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  let body: { itemId?: string; disposition?: string };
  try { body = await req.json(); } catch { return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); }
  if (!body.itemId) return NextResponse.json({ error: "itemId required" }, { status: 400 });
 
  const db = getDb();
  // Resolve the item, authorize on its collection, then assert it agrees with the URL.
  const item = await requireApiItemCapability(db, body.itemId, session.user.id, "preferences:write");
  if (item instanceof NextResponse) return item;
  if (item.collectionId !== id) return NextResponse.json({ error: "Not found" }, { status: 404 });
 
  try {
    const result = await DispositionController.fromDb(db).setDisposition(id, session.user.id, body);
    return NextResponse.json(result, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
}
 
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getSession();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const db = getDb();
  const access = await requireApiCollectionAccess(db, id, session.user.id);
  if (access instanceof NextResponse) return access;
  const disp = new URL(req.url).searchParams.get("disposition") ?? undefined;
  const list = await DispositionController.fromDb(db).listDispositions(
    id, session.user.id, disp === "set_aside" || disp === "deferred" ? disp : undefined,
  );
  return NextResponse.json(list);
}